package com.bbcare.followup.plat.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import redis.clients.jedis.JedisPool;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.SeqUtil;
import com.bbcare.followup.plat.entity.PtEvaluationManualGuide;
import com.bbcare.followup.plat.service.IEvaluationWorkOrderService;
import com.bbcare.followup.plat.service.IFollowEvaluationService;
import com.bbcare.followup.plat.service.IFollowQueueService;
import com.bbcare.followup.plat.store.ibatis.IEvaluationWorkOrderDAO;


/**
 * 
 * @name:         EvaluationWorkOrderService.java
 * @author:       tao
 * @createTime:   2017年10月11日
 * @description:  EvaluationWorkOrderService.java
 * @modify:
 *
 */
@Service
public class EvaluationWorkOrderService implements IEvaluationWorkOrderService {
	private final Log logger = LogFactory.getLog(EvaluationWorkOrderService.class);

	@Resource(name = "jedisPool")
	private JedisPool jedisPool;



	@Autowired
    private IFollowQueueService fllowQueueService;
	
	@Autowired
    private IFollowEvaluationService followEvaluationService;  
	
	@Autowired
    private IEvaluationWorkOrderDAO evaluationWorkOrderDAO;
	
	@Override
	public List<Map<String, Object>> getEvaluationMonthRecords(
			Map<String, Object> paramMap) throws Exception {
		List<Map<String, Object>>  list = new ArrayList<Map<String, Object>>();
		String queueId  = ((paramMap.get("queueId")!=null && !StringUtils.isEmpty(paramMap.get("queueId").toString()))) ? paramMap.get("queueId").toString() : null;
		
		List<String> queueIdArray = new ArrayList<String>();
		if(StringUtils.isEmpty(queueId)){
			// 根据当前登录账号获取，其可以查看的队列id
			queueIdArray = fllowQueueService.getQueueArrByAuthority(paramMap);
			if(CollectionUtils.isEmpty(queueIdArray)){
				logger.warn("该账号无可查看到的患者信息...arg==" + paramMap.toString());
				return list;
			}
		}else{
			queueIdArray.add(queueId);
		}
		
        paramMap.put("queueIdIn",queueIdArray);
        paramMap.put("userStatus",Constants.QUEUE_STATUS_NOMAL);
        int page =  (paramMap.get("page")!=null && !StringUtils.isEmpty(paramMap.get("page").toString())) ? Integer.parseInt(paramMap.get("page").toString()) : 1;
		int rows =  (paramMap.get("rows")!=null && !StringUtils.isEmpty(paramMap.get("rows").toString())) ? Integer.parseInt(paramMap.get("rows").toString()) : 10;
		
		paramMap.put("start", page);
		paramMap.put("end", rows);
		
		Object userNameObject = paramMap.get("userName");
		Object userName = (userNameObject!=null &&!StringUtils.isEmpty(userNameObject)) ? "%"+userNameObject.toString()+"%" : userNameObject ;
		
		Object phoneNo = paramMap.get("phoneNo");

		paramMap.put("userName",userName);
		paramMap.put("phoneNo",phoneNo);
		
		Map<String, Object> map = null;
		list = evaluationWorkOrderDAO.selectEvaluaTionOrderList(paramMap);
		if(!CollectionUtils.isEmpty(list)){
			for(int i = 0;i<list.size();i++){
				map = list.get(i);
				//监测时间
//				list.get(i).put("testTime",map.get("testTime").toString());
				list.get(i).put("createTime",DateUtil.getTimeStampSec(map.get("createTime").toString()));
				if(null != map.get("updateTime")){
					list.get(i).put("dealTime",DateUtil.getTimeStampSec(map.get("updateTime").toString()));
				}
				map = null;
			}
		}
		return list;
	}

	@Override
	public int getEvaluationMonthCount(Map<String, Object> paramMap)
			throws Exception {
		paramMap.put("userStatus",Constants.QUEUE_STATUS_NOMAL);
		int i = evaluationWorkOrderDAO.selectEvaluaTionOrderCount(paramMap);
		return i;
	}

	@Override
	public Map<String, Object> getEvaluationMonthRecordDetail(
			Map<String, Object> paramMap) throws Exception {
		Map<String, Object> map = evaluationWorkOrderDAO.selectEvaluaTionOrderDetail(paramMap);
		if(map != null){
			if(null != map.get("createTime")){
				map.put("createTime",DateUtil.getTimeStampSec(map.get("createTime").toString()));
			}
			if(null != map.get("remark1")){
				map.put("birthdayWeight",DateUtil.getTimeStampSec(map.get("remark1").toString()));
			}
		}
		return map;
	}

	@Override
	public Map<String, Object> getEvaluationMonthRecordResult(
			Map<String, Object> paramMap) throws Exception {
		String type = (String)paramMap.get("type");
//		String workOrderId = (String)paramMap.get("workOrderId");
//		String tenantId = (String)paramMap.get("tenantId");
		
		Map<String,Object> rspMap = new HashMap<String,Object>();
		Map<String,Object> guideMap = null;
		List<Map<String,Object>>  guideList= evaluationWorkOrderDAO.selectEvaluaTionManualGuide(paramMap);
		if(!CollectionUtils.isEmpty(guideList)){
			guideMap = guideList.get(0);
		}
		
		if("01".equals(type)){//查询生长发育
			List<Map<String,Object>> list = evaluationWorkOrderDAO.selectGrowthDetailByOrderId(paramMap);
			Map<String,Object> map = null;
			if(!CollectionUtils.isEmpty(list)){
				map = list.get(0);
				JSONObject  obj = JSON.parseObject(map.get("result").toString());
				JSONArray weightResult = obj.getJSONArray("weightResult");
				JSONArray heightResult = obj.getJSONArray("heightResult");
				JSONArray headtResult = obj.getJSONArray("headtResult");
				Map<String,Object> weightMap = new HashMap<String,Object>();
				if(null !=weightResult && weightResult.size()> 0){
					weightMap.put("percentileRange", weightResult.getJSONObject(0).get("percentileRange"));
				}
				weightMap.put("weight",map.get("weight"));
				Map<String,Object> heightMap = new HashMap<String,Object>();
				if(null !=heightResult && heightResult.size()> 0){
					heightMap.put("percentileRange", heightResult.getJSONObject(0).get("percentileRange"));
				}
				heightMap.put("height",map.get("height"));
				Map<String,Object> headtMap = new HashMap<String,Object>();
				if(null !=headtResult && headtResult.size()> 0){
					headtMap.put("percentileRange", headtResult.getJSONObject(0).get("percentileRange"));
				}
				headtMap.put("headCircumference",map.get("headCircumference"));
				
				Map<String,Object> result = new HashMap<String,Object>();
				result.put("heightMap",heightMap);
				result.put("weightMap",weightMap);
				result.put("headtMap",headtMap);
				
				rspMap.put("result",result);
				rspMap.put("evaluationId", map.get("growthRecordId"));
				if(null!=guideMap && !StringUtils.isEmpty(guideMap.get("guide"))){
					rspMap.put("guide",JSON.parseObject(guideMap.get("guide").toString()));
				}
			}
		}else if("02".equals(type)){//查询智能发育
			paramMap.put("evaluationType",Constants.FOLLOW_EVALUATION_PREGNANT_ASQ);
			List<Map<String,Object>> list = evaluationWorkOrderDAO.selectEvaluaTionDetailByOrderId(paramMap);
			if(!CollectionUtils.isEmpty(list)){
				JSONObject obj =JSON.parseObject(list.get(0).get("result").toString());
	            if(null != obj){
	            	 rspMap.put("result",obj.get("score"));
	            }
	            if(null!=guideMap && !StringUtils.isEmpty(guideMap.get("guide"))){
					rspMap.put("guide",JSON.parseObject(guideMap.get("guide").toString()));
				}
	            
	            //查询人工智能指导意见
	            paramMap.clear();
	            paramMap.put("evaluationId",list.get(0).get("answerId"));
	            Map<String,Object> aotoGuide = new HashMap<String,Object>();
	            List<Map<String,Object>> guidelist = followEvaluationService.getEvaluationGuides(paramMap);
	            for(int i =0;i<guidelist.size();i++){
	            	Map<String,Object> maptemp = guidelist.get(i);
	            	String moduleCode = (String)maptemp.get("moduleCode");
	            	String guideStr = (String)maptemp.get("guide");
	            	if(aotoGuide.containsKey(moduleCode)){
	            		guideStr =  aotoGuide.get(moduleCode) +";"+ guideStr;
	            		aotoGuide.put(moduleCode,guideStr);
	            	}else{
	            		aotoGuide.put(moduleCode,guideStr);
	            	}
	            }
	            rspMap.put("evaluationId", list.get(0).get("answerId"));
	            rspMap.put("aotuGuide",aotoGuide);
			}
		}else if("03".equals(type)){//查询养育环境
			paramMap.put("evaluationType",Constants.FOLLOW_EVALUATION_PREGNANT_AHEMD);
			List<Map<String,Object>> list = evaluationWorkOrderDAO.selectEvaluaTionDetailByOrderId(paramMap);
			if(!CollectionUtils.isEmpty(list)){
				JSONObject obj =JSON.parseObject(list.get(0).get("result").toString());
	            if(null != obj){
	            	rspMap.put("result",obj.get("score"));
	            }
	            if(null!=guideMap && !StringUtils.isEmpty(guideMap.get("guide"))){
					rspMap.put("guide",JSON.parseObject(guideMap.get("guide").toString()));
				}
	            
	            //查询人工智能指导意见
	            paramMap.clear();
	            paramMap.put("evaluationId",list.get(0).get("answerId"));
	            Map<String,Object> aotoGuide = new HashMap<String,Object>();
	            List<Map<String,Object>> guidelist = followEvaluationService.getEvaluationGuides(paramMap);
	            for(int i =0;i<guidelist.size();i++){
	            	Map<String,Object> maptemp = guidelist.get(i);
	            	String moduleCode = (String)maptemp.get("moduleCode");
	            	String guideStr = (String)maptemp.get("guide");
	            	if(aotoGuide.containsKey(moduleCode)){
	            		guideStr =  aotoGuide.get(moduleCode) +";"+ guideStr;
	            		aotoGuide.put(moduleCode,guideStr);
	            	}else{
	            		aotoGuide.put(moduleCode,guideStr);
	            	}
	            }
	            rspMap.put("evaluationId", list.get(0).get("answerId"));
	            rspMap.put("aotuGuide",aotoGuide);
			}
		}else if("04".equals(type) || "05".equals(type)){//查询健康指导 查询生长综合评估
			if(null!=guideMap && !StringUtils.isEmpty(guideMap.get("guide"))){
				rspMap.put("guide",JSON.parseObject(guideMap.get("guide").toString()));
			}
		}
//		rspMap.put("result",);
		return rspMap;
	}

	@Override
	public Map<String, Object> evaluationManualModify(
			Map<String, Object> paramMap) throws Exception {
		String type = (String)paramMap.get("type");
		String workOrderId = (String)paramMap.get("workOrderId");
//		String tenantId = (String)paramMap.get("tenantId");
		String guideStr = null;
		String evaluationId = (String)paramMap.get("evaluationId");
		String CreateTime = DateUtil.getSysDateA();
		String authorId = (String)paramMap.get("authorId");
		Object obj = null;
		if("01".equals(type)){//查询生长发育
			obj = paramMap.get("growthguide");
			if(!StringUtils.isEmpty(obj)){
				guideStr = paramMap.get("growthguide").toString();
			}
		}else if("02".equals(type)){
			obj = paramMap.get("asqguide");
			if(!StringUtils.isEmpty(obj)){
				guideStr = paramMap.get("asqguide").toString();
			}
		}else if("03".equals(type)){
			obj = paramMap.get("ahemdguide");
			if(!StringUtils.isEmpty(obj)){
				guideStr = paramMap.get("ahemdguide").toString();
			}
		}else if("04".equals(type)){
			obj = paramMap.get("healthguide");
			if(!StringUtils.isEmpty(obj)){
				guideStr = paramMap.get("healthguide").toString();
			}
		}else if("05".equals(type)){
			obj = paramMap.get("allguide");
			if(!StringUtils.isEmpty(obj)){
				guideStr = paramMap.get("allguide").toString();
			}
		}
		if(!StringUtils.isEmpty(guideStr)){
			List<Map<String,Object>> guideMap = evaluationWorkOrderDAO.selectEvaluaTionManualGuide(paramMap);
			if(!CollectionUtils.isEmpty(guideMap)){//修改
				Map<String,Object> updateMap = new HashMap<String,Object>();
				updateMap.put("updateTime",CreateTime);
				updateMap.put("updateAuthor",authorId);
				updateMap.put("guide",guideStr);
				updateMap.put("type",type);
				updateMap.put("workOrderId",workOrderId);
				evaluationWorkOrderDAO.updatePtEvaluationMunualGuide(updateMap);
			}else{ //新增
				PtEvaluationManualGuide guide = new  PtEvaluationManualGuide();
				guide.setId(SeqUtil.getSeqNo());
				guide.setCreateTime(CreateTime);
				guide.setCreateAuthor(authorId);
				guide.setEvaluationId(evaluationId);
				guide.setGuide(guideStr);
//				guide.setRemark(remark);
				guide.setType(type);
				guide.setWorkOrderid(workOrderId);
				List<PtEvaluationManualGuide> guides = new ArrayList<PtEvaluationManualGuide>();
				guides.add(guide);
				evaluationWorkOrderDAO.saveBatchPtEvaluationMunualGuide(guides);
			}
		}
		return null;
	}

	@Override
	public Map<String,Object> evaluationMonthRecordModify(
			Map<String, Object> paramMap) throws Exception {
		String doctorName = (String)paramMap.get("doctorName");
		String doctorId = (String)paramMap.get("doctorId");
		String createTime = DateUtil.getSysDateA();
		String authorId = (String)paramMap.get("authorId");
		String workOrderId = (String)paramMap.get("workOrderId");
		String status = (String)paramMap.get("status");
		Map<String,Object> updateMap = new HashMap<String,Object>();
		
		updateMap.put("updateTime",createTime);
		updateMap.put("updateAuthor",authorId);
		updateMap.put("doctorName",doctorName);
		updateMap.put("doctorId",doctorId);
		updateMap.put("status",status);
		if(Constants.EVLATATION_WORKORDER_STATUS_SENDTODOCTOR.equals(status)){
			updateMap.put("sendDoctorTime",createTime);//发送给医生
		}else if(Constants.EVLATATION_WORKORDER_STATUS_DO.equals(status)){
			updateMap.put("dealTime",createTime);//客服运营提交资料
		}else if(Constants.EVLATATION_WORKORDER_STATUS_DOCTORCONFIRM.equals(status)){
			updateMap.put("doctorConfirmTime",createTime);//发送给医生
		}else if(Constants.EVLATATION_WORKORDER_STATUS_SENDUSER.equals(status)){
			updateMap.put("sendUserTime",createTime);//发送用户
		}else if(Constants.EVLATATION_WORKORDER_STATUS_COMPLETE.equals(status)){
			updateMap.put("userReceiveTime",createTime);//完成
		}
		updateMap.put("workOrderId",workOrderId);
		
		evaluationWorkOrderDAO.updateEvaluaTationOrder(updateMap);
		return null;
	}

	@Override
	public List<Map<String, Object>> getEvaluationDoctorList(
			Map<String, Object> paramMap) throws Exception {
		
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		String queueId  = ((paramMap.get("queueId")!=null && !StringUtils.isEmpty(paramMap.get("queueId").toString()))) ? paramMap.get("queueId").toString() : null;
		
		List<String> queueIdArray = new ArrayList<String>();
		if(StringUtils.isEmpty(queueId)){
			// 根据当前登录账号获取，其可以查看的队列id
			queueIdArray = fllowQueueService.getQueueArrByAuthority(paramMap);
			if(CollectionUtils.isEmpty(queueIdArray)){
				logger.warn("该账号无可查看到的患者信息...arg==" + paramMap.toString());
				return list;
			}
		}else{
			queueIdArray.add(queueId);
		}
		
        paramMap.put("queueIdIn",queueIdArray);
        paramMap.put("status",Constants.QUEUE_STATUS_NOMAL);
        
        list =  evaluationWorkOrderDAO.queueEvaluationDoctors(paramMap);
        
		return list;
	}

	@Override
	public Map<String, Object> getEvaluationRecordProjects(
			Map<String, Object> paramMap) throws Exception {
		List<Map<String,Object>> list = evaluationWorkOrderDAO.selectEvaluaTionDetailByOrderId(paramMap);
		String asq ="";
		String ahemd ="";
		Map<String,Object> map= new HashMap<String,Object>();
		if(!CollectionUtils.isEmpty(list)){
			for(int i =0;i<list.size();i++){
				if(Constants.FOLLOW_EVALUATION_PREGNANT_ASQ.equals(list.get(i).get("type"))){
					asq = (String)list.get(i).get("answerId");
				}else if(Constants.FOLLOW_EVALUATION_PREGNANT_AHEMD.equals(list.get(i).get("type"))){
					ahemd = (String)list.get(i).get("answerId");
				}
			}
		}
		map.put("asq", asq);
		map.put("ahemd", ahemd);
		return map;
	}
	
	
	
}
